<template>
    <n-upload
        :key="fileList[0]?.id"
        :action="`${uploadFile}/images`"
        method="POST"
        :headers="headers"
        :default-file-list="fileList"
        list-type="image-card"
        :max="1"
        v-bind="attrs"
        @finish="onFinish"
        @error="onError"
        @remove="onRemove"
    >
        点击上传
    </n-upload>
</template>

<script setup>
import { createDiscreteApi } from 'naive-ui';
import { computed, ref, useAttrs } from 'vue';
import { getToken } from '@/utils/auth';
import { uploadFile, viewFile } from '@/config';

const attrs = useAttrs();
const { message } = createDiscreteApi(['message']);
const emits = defineEmits('update:value');
const props = defineProps({
    value: {
        type: Object,
        default: () => ({})
    }
});
const headers = ref({
    token: getToken()
});
const fileList = computed(() => {
    console.log(`output->props`, props.value);
    if (Object.keys(props.value).length > 0) return [props.value];
    return [];
});
const onFinish = ({ file }) => {
    emits('update:value', {
        id: file.id,
        name: file.name,
        status: file.status,
        type: file.type,
        url: `${viewFile}/images/${file.name}`
    });
};
const onRemove = () => {
    emits('update:value', {});
};
const onError = () => {
    message.error('上传失败！');
};
</script>
<style lang="less" scoped></style>
